package com.egg.ylt.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.fragment.FRA_Center;
import com.egg.ylt.fragment.FRA_Find;
import com.egg.ylt.fragment.FRA_Health;
import com.egg.ylt.fragment.FRA_Home;
import com.egg.ylt.fragment.FRA_Order;
import com.egg.ylt.fragment.FRA_Record;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.eventbus.EventCenter;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_HomePage extends BaseActivity {


    @BindView(R.id.home_consult)
    LinearLayout homeConsult;
    @BindView(R.id.home_health)
    LinearLayout homeHealth;
    @BindView(R.id.home_order)
    LinearLayout homeOrder;
    @BindView(R.id.home_center)
    LinearLayout homeCenter;
    @BindView(R.id.tab)
    LinearLayout tab;
    @BindView(R.id.home_frame_layout)
    FrameLayout homeFrameLayout;
    @BindView(R.id.rl_view)
    RelativeLayout rlView;
    @BindView(R.id.iv_health)
    ImageView ivHealth;
    @BindView(R.id.tv_health)
    TextView tvHealth;
    @BindView(R.id.iv_order)
    ImageView ivOrder;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.iv_center)
    ImageView ivCenter;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.iv_appointment)
    ImageView ivAppointment;
    @BindView(R.id.tv_appointment)
    TextView tvAppointment;
    @BindView(R.id.iv_consult)
    ImageView ivConsult;
    @BindView(R.id.tv_consult)
    TextView tvConsult;
    @BindView(R.id.tv_login_immediate)
    TextView tvLoginImmediate;
    @BindView(R.id.ll_floating_tips)
    LinearLayout llFloatingTips;
    //fragment对象
    private Fragment currentFragment;

    //    private FRA_Appointment fra_appointment;
    private FRA_Center fra_center;
    private FRA_Order fra_order;
    private FRA_Health fra_health;
    private FRA_Record fra_record;
    //    private FRA_News fra_consult;
    //标记
    private ImageView ivCurrent;
    private TextView tvCurrent;

    private FRA_Home mFraHome;
    private FRA_Find mFraFind;

    public static int GO_TO_ORDER_FRAGMENT = 0;
    public static int GO_TO_HOME_FRAGMENT = 1;
    private int mType = -15;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    private AppSharedPreferences mSp;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_home_page;
    }

    @Override
    protected View getLoadingTargetView() {
        return rlView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置初始显示的页面导航图标
        if (ivCurrent != null) {
            ivCurrent.setSelected(true);
        }
        if (tvCurrent != null) {
            tvCurrent.setSelected(true);
        }

    }

    @Override
    protected void initViewsAndEvents() {

        mSp = new AppSharedPreferences(mContext);

        //Android6.0以上系统可以把状态栏文字和图标换成深色
        StatusBarUtil.setStatusBarColor(this, R.color.color_E6E6E6);
        StatusBarUtil.StatusBarLightMode(this);
//        CustomUtils.setImmersiveStatusBar(mContext, rlView);

        // 立即登录浮窗显示隐藏
        mSp.putBoolean("is_show_floating_button", true);
        llFloatingTips.setVisibility(TextUtils.isEmpty(Constants.TOKEN) ? View.VISIBLE : View.GONE);

        //初始化fragment
//        fra_appointment = new FRA_Appointment();
        fra_center = new FRA_Center();
        fra_order = new FRA_Order();
        fra_health = new FRA_Health();
//        fra_consult = new FRA_News();
        mFraFind = new FRA_Find();

        mFraHome = new FRA_Home();

        fra_record = new FRA_Record();

        //设置初始显示的页面导航图标
        ivConsult.setSelected(true);
        ivCurrent = ivConsult;
        tvConsult.setSelected(true);
        tvCurrent = tvConsult;

        // 设置主页显示的页面
        if (!mFraHome.isAdded()) {
            currentFragment = mFraHome;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.home_frame_layout, mFraHome);
            transaction.commitAllowingStateLoss();
        }
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.EXIT_LOGIN_GO_HOME:
                ivCurrent.setSelected(false);
                tvCurrent.setSelected(false);
                ivConsult.setSelected(true);
                ivCurrent = ivConsult;
                tvConsult.setSelected(true);
                tvCurrent = tvConsult;
                switchContent(currentFragment, mFraHome);

                // 立即登录浮窗显示隐藏
                mSp.putBoolean("is_show_floating_button", true);
                llFloatingTips.setVisibility(TextUtils.isEmpty(Constants.TOKEN) ? View.VISIBLE : View.GONE);
                break;
        }
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }


    @OnClick({R.id.home_consult, R.id.home_health, R.id.home_order, R.id.home_center,
            R.id.tv_login_immediate, R.id.iv_close})
    public void onClick(View view) {
        ivCurrent.setSelected(false);
        tvCurrent.setSelected(false);

        switch (view.getId()) {
            case R.id.home_consult://咨询
                ivConsult.setSelected(true);
                ivCurrent = ivConsult;
                tvConsult.setSelected(true);
                tvCurrent = tvConsult;
                switchContent(currentFragment, mFraHome);
                break;
            case R.id.home_health://健康
                ivHealth.setSelected(true);
                ivCurrent = ivHealth;
                tvHealth.setSelected(true);
                tvCurrent = tvHealth;
                switchContent(currentFragment, mFraFind);
                break;
            case R.id.home_appointment://预约
                //属性动画实现，但是只执行一次
//                ivAppointment.animate().rotation(180);
                //补间动画
//                Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_home_iv_appointment);
//                LinearInterpolator lin = new LinearInterpolator();
//                operatingAnim.setInterpolator(lin);
//                operatingAnim.setFillAfter(true);
//                if (operatingAnim != null && !fra_appointment.isVisible()) {
//                    ivAppointment.startAnimation(operatingAnim);
//                }
//                ivAppointment.setSelected(true);
//                ivCurrent = ivAppointment;
//                tvAppointment.setSelected(true);
//                tvCurrent = tvAppointment;
//                switchFragmentContent(currentFragment, fra_appointment);
                break;
            case R.id.home_order://订单 1.4之后是健康，此处需要修改
                ivOrder.setSelected(true);
                ivCurrent = ivOrder;
                tvOrder.setSelected(true);
                tvCurrent = tvOrder;
//                switchContent(currentFragment, fra_record);
                switchContent(currentFragment, fra_health);
                break;
            case R.id.home_center://个人
                ivCenter.setSelected(true);
                ivCurrent = ivCenter;
                tvCenter.setSelected(true);
                tvCurrent = tvCenter;
                switchContent(currentFragment, fra_center);
                break;
            case R.id.tv_login_immediate:
                readyGo(ACT_UserLogin.class);
                break;
            case R.id.iv_close:
                llFloatingTips.setVisibility(View.GONE);
                mSp.putBoolean("is_show_floating_button", false);
                break;
        }
    }

    /**
     * 切换Fragment
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to) {
        if (currentFragment != to) {
            currentFragment = to;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from).add(R.id.home_frame_layout, to).commitAllowingStateLoss(); // 隐藏当前的fragment
                // ，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
//                refreshData(to);
            }

            // 未登录 && 停留在首页 && 用户没有手动关闭过，才展示浮窗
            if (to instanceof FRA_Home
                    && TextUtils.isEmpty(Constants.TOKEN)
                    && mSp.getBoolean("is_show_floating_button")) {
                llFloatingTips.setVisibility(View.VISIBLE);
            } else {
                llFloatingTips.setVisibility(View.GONE);
            }

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.makeText(mContext, "再按一次退出程序", false);
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mType = intent.getIntExtra("type", -1);
        ivCurrent.setSelected(false);
        tvCurrent.setSelected(false);
        if (mType == GO_TO_ORDER_FRAGMENT) {
            ivOrder.setSelected(true);
            ivCurrent = ivOrder;
            tvOrder.setSelected(true);
            tvCurrent = tvOrder;
            switchContent(currentFragment, fra_order);
        }

        if (mType == GO_TO_HOME_FRAGMENT) {
            ivConsult.setSelected(true);
            ivCurrent = ivConsult;
            tvConsult.setSelected(true);
            tvCurrent = tvConsult;
            switchContent(currentFragment, mFraHome);
        }

        // 立即登录浮窗显示隐藏
        mSp.putBoolean("is_show_floating_button", true);
        llFloatingTips.setVisibility(TextUtils.isEmpty(Constants.TOKEN) ? View.VISIBLE : View.GONE);
    }


}
